document.addEventListener("DOMContentLoaded", function () {
    const display = document.getElementById("calcDisplay");
    const buttons = document.querySelectorAll(".calc-btn");

    let currentInput = "0";
    let previousInput = "";
    let operation = null;
    let resetInput = false;

    // 更新显示
    function updateDisplay() {
        if (Number.isInteger(parseFloat(currentInput))) {
            display.value = parseInt(currentInput);
            return;
        }
        display.value = parseFloat(currentInput)
            .toFixed(10)
            .toString()
            .replace(/(\.\d*?)0+$/, "$1")
            .replace(/\.$/, "");
    }

    // 处理数字输入
    function inputNumber(number) {
        if (currentInput === "0" || resetInput) {
            currentInput = number;
            resetInput = false;
        } else {
            currentInput += number;
        }
    }

    // 处理小数点
    function inputDecimal() {
        if (resetInput) {
            currentInput = "0.";
            resetInput = false;
            return;
        }

        if (!currentInput.includes(".")) {
            currentInput += ".";
        }
    }

    // 处理操作符
    function handleOperator(op) {
        if (op === "C") {
            // 清除所有
            currentInput = "0";
            previousInput = "";
            operation = null;
            return;
        }

        if (op === "CE") {
            // 清除当前输入
            currentInput = "0";
            return;
        }

        if (op === "%") {
            // 百分比计算
            currentInput = (parseFloat(currentInput) / 100).toString();
            return;
        }

        if (op === "sqrt") {
            // 平方根计算
            currentInput = Math.sqrt(parseFloat(currentInput)).toString();
            return;
        }

        if (op === "=") {
            // 执行计算
            if (operation && previousInput) {
                calculate();
            }
            return;
        }

        // 存储当前操作
        if (previousInput && !resetInput) {
            calculate();
        }

        previousInput = currentInput;
        operation = op;
        resetInput = true;
    }

    // 执行计算
    function calculate() {
        let result;
        const prev = parseFloat(previousInput);
        const current = parseFloat(currentInput);

        if (isNaN(prev) || isNaN(current)) return;

        switch (operation) {
            case "+":
                result = prev + current;
                break;
            case "-":
                result = prev - current;
                break;
            case "*":
                result = prev * current;
                break;
            case "/":
                result = prev / current;
                break;
            default:
                return;
        }

        currentInput = result.toString();
        operation = null;
        previousInput = "";
        resetInput = true;
    }

    // 为按钮添加事件监听
    buttons.forEach((button) => {
        button.addEventListener("click", () => {
            const value = button.getAttribute("data-value");

            if (!isNaN(value) || value === ".") {
                if (value === ".") {
                    inputDecimal();
                } else {
                    inputNumber(value);
                }
            } else {
                handleOperator(value);
            }

            updateDisplay();
        });
    });

    // 初始化显示
    updateDisplay();

    // 键盘支持
    document.addEventListener("keydown", function (e) {
        const key = e.key;

        if ((key >= "0" && key <= "9") || key === ".") {
            const button = document.querySelector(
                `.calc-btn[data-value="${key}"]`
            );
            if (button) button.click();
        } else if (key === "+" || key === "-" || key === "*" || key === "/") {
            const button = document.querySelector(
                `.calc-btn[data-value="${key}"]`
            );
            if (button) button.click();
        } else if (key === "Enter") {
            const button = document.querySelector(`.calc-btn[data-value="="]`);
            if (button) button.click();
        } else if (key === "Escape") {
            const button = document.querySelector(`.calc-btn[data-value="C"]`);
            if (button) button.click();
        } else if (key === "Backspace") {
            const button = document.querySelector(`.calc-btn[data-value="CE"]`);
            if (button) button.click();
        }
    });
});
